#include "stdafx.h"
#include "StreamServer.h"
#include "Configure.h"
#include "Error.h"
#include "SchemaManager.h"
#include "QueryManager.h"
#include "PlanManager.h"
#include "SemanticInterpreter.h"
#include "LogPlanGenerator.h"
#include "TableSource.h"
#include "QueryOutput.h"
#include "BSReader.h"
#include "BSValue.h"
#include "SchemaManager.h"
#include "Node.h"
#include "mc_driver.hpp"
StreamServer::StreamServer(void) 
{
}

StreamServer::~StreamServer(void)
{
}


void StreamServer::registerConfigureFile(void)
{
    std::cout<<"register configure file"<<std::endl;
	Configure::getInstance();
}


int StreamServer::beginAppSpecification() 
{
	//schema manager
	this->schemaManager.reset( new SchemaManager());
	if(!this->schemaManager)
	{
		return INTERNAL_ERR;
	}
	this->queryManager.reset(new QueryManager());
	if(!this->queryManager)
	{
		return INTERNAL_ERR;
	}
	this->planManager.reset(new PlanManager());
	if(!this->planManager)
	{
		return INTERNAL_ERR;
	}
	this->semanticInterpreter.reset(new SemanticInterpreter());
	if(!this->semanticInterpreter)
	{
		return INTERNAL_ERR;
	}
	this->logPlanGenerator.reset(new LogPlanGenerator());
	if(!this->logPlanGenerator)
	{
		return INTERNAL_ERR;
	}
	return 0;

}
int StreamServer::endAppSpecification() 
{
	return 0;
}
int StreamServer::beginExecution() 
{
	return 0;
}
int StreamServer::registerSchema() 
{
	std::cout<<"register schema"<<std::endl;
	std::string patternFilePath = Configure::getInstance()->getConfigureValue("schema_file");
	BSReader bsReader;
	BSValue schemaValue;
	std::ifstream is;  
	is.open (patternFilePath, std::ios::binary );    

	bsReader.parse(is,schemaValue);

	for(unsigned int i = 0; i< schemaValue.size();i++)
	{
		BSValue schema = schemaValue[i];
		std::string id = schema["id"].asString();
		transform(id.begin(), id.end(), id.begin(), ::tolower);
		Schema * s =  new Schema(schema);
		this->schemaManager->addSchema(id,s);
	}

	return 0;
}

int StreamServer::registerQuery() 
{
	NODE *parseTree=NULL;

	MC::MC_Driver driver;

	std::cout<<"register query"<<std::endl;
	std::string patternFilePath = Configure::getInstance()->getConfigureValue("query_file");

	BSReader bsReader;
	BSValue queryValue;
	std::ifstream is;  
	is.open (patternFilePath, std::ios::binary );   

	bsReader.parse(is,queryValue);
	for(unsigned int i = 0; i< queryValue.size();i++)
	{
		BSValue query = queryValue[i];
		std::string id = query["id"].asString();
		std::string content = query["content"].asString();
		transform(id.begin(), id.end(), id.begin(), ::tolower);
		transform(content.begin(), content.end(), content.begin(), ::tolower);

		parseTree = driver.parse(content.c_str());
		if (!parseTree) {
			return PARSE_ERR;
		}
		

	}
	//driver.parse( patternFilePath.c_str() );

	// std::cout << "Results\n";

	// driver.print(std::cout) << "\n";

	return 0;
}
